package com.yeskery.nut.core;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.extend.responsive.JsonResponsive;
import com.yeskery.nut.extend.responsive.JsonResponsivePlugin;

import java.util.logging.Logger;

/**
 * Nut响应对象
 * @author Yeskery
 * 2023/5/16
 */
public abstract class BaseNutResponse implements Response {

    /** Nut应用对象 */
    private final NutApplication nutApplication;

    /**
     * 构建Nut响应对象
     * @param nutApplication Nut应用对象
     */
    public BaseNutResponse(NutApplication nutApplication) {
        this.nutApplication = nutApplication;
    }

    @Override
    public void writeJsonFromObject(Object object) {
        if (object == null) {
            writeJson("null");
            return;
        }
        if (nutApplication.getNutWebConfigure().getPluginManager().containPlugin(JsonResponsivePlugin.class)) {
            JsonResponsive responsive = ((Execution) nutApplication.getNutWebConfigure().getDispatcher()).getBindContext().getObject(JsonResponsive.class);
            writeJson(responsive.getResponsiveConvert().convertTo(object));
        } else {
            Logger.getLogger(this.getClass().getName()).info("Use Response Method [writeJsonFromObject], But Unable Find Plugin["
                    + JsonResponsivePlugin.class + "]");
            writeJson(object.toString());
        }
    }

    /**
     * 获取Nut应用对象
     * @return Nut应用对象
     */
    protected NutApplication getNutApplication() {
        return nutApplication;
    }
}
